import { http } from "./request";
import axios from "axios";
import { ElNotification, ElMessageBox, ElMessage, ElLoading } from 'element-plus'
import { ref } from 'vue'
import { saveAs } from 'file-saver'
// 登录
export function getLogin(data:any) {
  return http({
    url: `/api/admin.php`, //此处为自己请求地址
    method: "post",
    data: data,
  });
}
//  订单查询  
export function getOrder(data:any) {
  return http({
    url: `/api/order.php`, //此处为自己请求地址
    method: "post",
    data: data,
  });
}
 
// 上传
export function getOrderimport(data:any) {
  return http({
    url: `/api/order.php?type=orderimport`, //此处为自己请求地址
    method: "post",
    data: data,
  });
}
// 上传运费
export function getOrderimportfreight(data:any) {
  return http({
    url: `/api/order.php?type=orderimportfreight`, //此处为自己请求地址
    method: "post",
    data: data,
  });
}
 
// 店铺
export function getShop(data:any) {
  return http({
    url: `/api/shop.php`, //此处为自己请求地址
    method: "post",
    data: data,
  });
}
 
/**
* 参数处理
* @param {*} params  参数
*/
export function tansParams(params:any) {
  let result = ''
  for (const propName of Object.keys(params)) {
    const value = params[propName];
    var part = encodeURIComponent(propName) + "=";
    if (value !== null && value !== "" && typeof (value) !== "undefined") {
      if (typeof value === 'object') {
        for (const key of Object.keys(value)) {
          if (value[key] !== null && value[key] !== "" && typeof (value[key]) !== 'undefined') {
            let params = propName + '[' + key + ']';
            var subPart = encodeURIComponent(params) + "=";
            result += subPart + encodeURIComponent(value[key]) + "&";
          }
        }
      } else {
        result += part + encodeURIComponent(value) + "&";
      }
    }
  }
  return result
}

// 验证是否为blob格式
export async function blobValidate(data:any) {
  try {
    const text = await data.text();
    JSON.parse(text);
    return false;
  } catch (error) {
    return true;
  }
}
// 通用下载方法
let downloadLoadingInstance = '' as any;
const errorCode = {
  '401': '认证失败，无法访问系统资源',
  '403': '当前操作没有权限',
  '404': '访问资源不存在',
  'default': '系统未知错误，请反馈给管理员'
}

export function download(url:any, params:any, filename:any) {
  const service = axios.create({
    baseURL: import.meta.env.VITE_URL_BASE, // api 的 base_url 注意 vue3 .env文件有强制性的 VITE_ 开头
    //   baseURL: 'https://www.baidu.com/api',  // 固定api
    timeout: 80000, // request timeout
  });
  downloadLoadingInstance = ElLoading.service({ text: "正在下载数据，请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
  return service.post(url, params, {
    transformRequest: [(params) => { return tansParams(params) }],
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    responseType: 'blob'
  }).then(async (data:any) => {
    const isLogin = await blobValidate(data);
    if (isLogin) {
      const blob = new Blob([data])
      saveAs(blob, filename)
    } else {
      const resText = await data.text();
      const rspObj = JSON.parse(resText);
      const errMsg = errorCode['default']
      ElMessage.error(errMsg);
    }
    downloadLoadingInstance.close();
  }).catch((r) => {
    console.error(r)
    ElMessage.error('下载文件出现错误，请联系管理员！')
    downloadLoadingInstance.close();
  })
}